﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoKnow.CloudEdu.CMS.Host.Models;
using DoKnow.CloudEdu.Common.Attrs;
using DoKnow.CloudEdu.Common.Consts;
using DoKnow.CloudEdu.Common.Enums;
using DoKnow.CloudEdu.DataContract.Model.Base;
using DoKnow.Common.Utility;
using DoKnow.Common.Utility.EnDe;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Webdiyer.WebControls.Mvc;

namespace DoKnow.CloudEdu.CMS.Host.Controllers
{
    public class BsUserController : BaseController
    {
        //
        // GET: /BsUser/

        public ActionResult Index(BSUserPageInfo request)
        {
            if (null != TempData["Msg"])
            {
                ViewBag.Msg = TempData["Msg"].ToString();
            }
            return QueryByUser(request);
        }
        [MenuItem("~/BsUser/Index")]
        public ActionResult QueryByUser(BSUserPageInfo request)
        {
            UserDatas users = HttpHelper.Post<UserDatas>(Server + ServicePath.UserRead,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "RetrieveUsers",
                    Pars = 
                      new {
                          user = EmitHelper.Map<BSUserPageInfo,BSUserInfo>(request),
                          page = EmitHelper.Map<BSUserPageInfo, PageInfo>(request)
                          } 
                }));
            if(null != users && null != users.UserEntitys && users.UserEntitys.Count >0)
            {
                var model = new PagedList<BSUserPageInfo>(EmitHelper.Map<BSUserInfo,BSUserPageInfo>(users.UserEntitys), request.PageIndex, request.PageSize, users.Total);
                return View("Index", model);
            }
            return View("Index"); 
        }
        [MenuItem("~/BsUser/Index")]
        public ActionResult Add()
        {
            if (null != TempData["Msg"])
            {
                ViewBag.Msg = TempData["Msg"].ToString();
            }
            ViewBag.ComStatus = EnumHelper.GetSelectList<EnumHelper.CommonStatus>();
            return View("Add", new BSUserInfo());
        }
        [MenuItem("~/BsUser/Index")]
        public ActionResult AddSave(BSUserInfo model)
        {
            //var managerClient = new BsUserManagerClient();
            model.Creator = model.Modifier = CurrentUser.UserEntity.Code;
            model.CreateTime = model.ModifyTime = System.DateTime.Now;
            //model.STATUS = (int)EnumHelper.CommonStatus.Active;
            var response = HttpHelper.Post(Server + ServicePath.UserRead,
                    JsonConvert.SerializeObject(
                    new
                    {
                        ActionName = "CreateUser",
                        Pars =
                          new
                          {
                              user = model
                          }
                    }, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
            if (!response.IsSuccess)
            {
                ViewBag.ComStatus = EnumHelper.GetSelectList<EnumHelper.CommonStatus>(model.Status.ToString());
                ViewBag.ErrMsg = string.IsNullOrEmpty(response.ErrMsg) ? string.Empty : (response.ErrMsg + ",") + "新增失败！";
                return View("Add", model);
            }
            else
            {
                TempData["Msg"] = "新增成功！";
                return RedirectToAction("Index");
            }
        }
        [MenuItem("~/BsUser/Index")]
        public ActionResult Edit(int id,string code,string mobile)
        {
            var model = HttpHelper.Post<BSUserInfo>(Server + ServicePath.UserRead,
                    JsonConvert.SerializeObject(
                    new
                    {
                        ActionName = "RetrieveUser",
                        Pars =
                          new
                          {
                              user = new BSUserInfo() { ID = id }
                          }
                    }));
            if (model != null)
            {
                ViewBag.ComStatus = EnumHelper.GetSelectList<EnumHelper.CommonStatus>(model.Status.ToString());
                return View("Edit", model);
            }
            else
            {
                TempData["Msg"] = "该用户已不存在！";
                return RedirectToAction("Index", new {Code=code,Mobile=mobile });
            }
        }
        [MenuItem("~/BsUser/Index")]
        public ActionResult EditSave(BSUserInfo model)
        {
            //var managerClient = new BsUserManagerClient();
            model.Modifier = CurrentUser.UserEntity.Code;
            model.ModifyTime = System.DateTime.Now;
            //model.STATUS = (int)EnumHelper.CommonStatus.Active;
            var response = HttpHelper.Post(Server + ServicePath.UserRead,
                    JsonConvert.SerializeObject(
                    new
                    {
                        ActionName = "UpdateUser",
                        Pars =
                          new
                          {
                              user = model
                          }
                    }, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
            if (!response.IsSuccess)
            {
                ViewBag.ErrMsg = string.IsNullOrEmpty(response.ErrMsg) ? string.Empty : (response.ErrMsg + ",") + "编辑失败！";
                ViewBag.ComStatus = EnumHelper.GetSelectList<EnumHelper.CommonStatus>(model.Status.ToString());
                return View("Edit", model);
            }
            else
            {
                TempData["Msg"] = "编辑成功！";
                return RedirectToAction("Index");
            }
        }

        [MenuItem("~/BsUser/Index")]
        public ActionResult Delete(int id)
        {
            var response = HttpHelper.Post(Server + ServicePath.UserWrite,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "DeleteUser",
                    Pars =
                      new
                      {
                          ID = id
                      }
                }));
            if (response.IsSuccess)
            {
                TempData["Msg"] = "删除成功！";
                return RedirectToAction("Index");
            }
            else
            {
                TempData["Msg"] = string.IsNullOrEmpty(response.ErrMsg)?string.Empty:(response.ErrMsg+",")+"删除失败！";
                return RedirectToAction("Index");
            }
        }
        [MenuItem("~/Home/Index")]
        public ActionResult ChangePWD()
        {
            PwdModel model = new PwdModel();
            model.ID = CurrentUser.UserEntity.ID;
            model.Name = CurrentUser.UserEntity.RealName;
            return View("ChangePWD", model);
        }
        [HttpPost]
        public ActionResult ChangePWD(PwdModel mode)
        {
            if (mode.NewPWD != mode.ConfirmPWD)
            {
                ViewBag.ErrMsg = "新密码与确认新密码不一致！";
                return View("ChangePWD", mode);
            }
            var response = HttpHelper.Post(Server + ServicePath.UserRead,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "UpdatePassword",
                    Pars =
                    new
                    {
                        userID = CurrentUser.UserEntity.ID,
                        oldPassword = mode.OldPWD,
                        newPassword = mode.NewPWD
                    }
                }));
            if(response.IsSuccess)
            {
                Request.Cookies.Remove(CookiesKey.LoginToken);
                return RedirectToAction("Login", "Home");
            }
            else
            {
                ViewBag.ErrMsg = response.ErrMsg+"原始密码不正确"; 
                return View(mode);
            }
        }
        public ActionResult GetUserCategroy()
        {
            var categorys = EnumHelper.GetList(typeof(EnumHelper.UserCategory));
            var result = Json(categorys);
            return result;
        }
    }
}
